package excel

import (
	"easyVolunteer/model"
	"easyVolunteer/utils/errno"
	"easyVolunteer/utils/upload"
	"fmt"
	"github.com/xuri/excelize/v2"
	"log"
	"strconv"
	"time"
)

const sheetName = "时长汇总"

var colWidth = map[string]float64{
	"A": 15,
	"B": 5,
	"C": 20,
	"D": 25,
	"E": 35,
	"F": 15,
	"G": 7,
	"H": 40,
}

func WriteExcel(u []model.User) (string, *errno.Errno) {
	f := excelize.NewFile()
	f.DeleteSheet("Sheet1") //删除默认的第一个表
	_ = f.NewSheet(sheetName)
	for k, v := range colWidth {
		err := f.SetColWidth(sheetName, k, k, v)
		if err != nil {
			log.Println("设置列宽失败")
		}
	}

	rowIndex := 1
	for _, v := range u {
		// 即使活动总数为零也要写入记录
		if len(v.Activities) == 0 {
			writeUserInfo(rowIndex, v, f)
			rowIndex++
			continue
		}

		for _, a := range v.Activities {
			writeUserInfo(rowIndex, v, f)
			writeActivityINfo(rowIndex, a, f)
			rowIndex++
		}
	}
	//f.SetActiveSheet(index)

	filePath := "static/志愿者/时长汇总" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
	//fmt.Println(filePath)
	if err := f.SaveAs(filePath); err != nil {
		fmt.Println(err)
		fmt.Println("dfsf")
	}

	err := f.Close()
	if err != nil {
		fmt.Println("关闭文件失败")
		return "", nil
	}

	url, e := upload.UpLoadToOss(filePath)
	if e != errno.OK {
		return "生成错误", errno.Fail
	}

	return url, errno.OK
}

func writeUserInfo(row int, u model.User, f *excelize.File) {
	err := f.SetCellValue(sheetName, "A"+strconv.Itoa(row), u.UserID)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = f.SetCellValue(sheetName, "B"+strconv.Itoa(row), u.TotalHours)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = f.SetCellValue(sheetName, "C"+strconv.Itoa(row), "未参加活动")
	if err != nil {
		fmt.Println(err)
		return
	}
}
func writeActivityINfo(row int, a model.Activity, f *excelize.File) {
	err := f.SetCellValue(sheetName, "C"+strconv.Itoa(row), a.ActivityID)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = f.SetCellValue(sheetName, "D"+strconv.Itoa(row), a.Start)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = f.SetCellValue(sheetName, "E"+strconv.Itoa(row), a.End)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = f.SetCellValue(sheetName, "F"+strconv.Itoa(row), a.OwnerID)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = f.SetCellValue(sheetName, "G"+strconv.Itoa(row), a.Duration)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = f.SetCellValue(sheetName, "H"+strconv.Itoa(row), a.Name)
	if err != nil {
		fmt.Println(err)
		return
	}
	err = f.SetCellValue(sheetName, "I"+strconv.Itoa(row), a.Comments)
	if err != nil {
		fmt.Println(err)
		return
	}
}

func TestUpload() {
	upload.UpLoadToOss("./结果.xlsx")
}
